<?php
require_once __DIR__ . '/wxToken.php';
require_once __DIR__ . '/Request.php';
require_once __DIR__ . '/../php_lib/WxSign.php';


class WxApi {
    public $appid, $appSecret, $tokenName, $token;
    function __construct($appid, $appSecret, $tokenName) {
        $this->appid = $appid;
        $this->appSecret = $appSecret;
        $this->tokenName = $tokenName;
        $this->token = new WxToken($appid, $appSecret, $tokenName);
    }
    /**
     * 验证签名
     * @return [type] [description]
     */
    function _checkSignature() {
        //获取由微信服务器发过来的数据
        $signature = $_GET['signature'] ?? null;
        $timestamp = $_GET['timestamp'] ?? null;
        $nonce = $_GET['nonce'] ?? null;
        //开始验证数据
        $tmp_arr =  array($this->token->token(), $timestamp, $nonce);

        var_dump($tmp_arr);
        sort($tmp_arr, SORT_STRING);
        $tmp_str = implode($tmp_arr);
        $tmp_str = sha1($tmp_str);
        //对比数据
        if ($signature == $tmp_str) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 获得随机字符串
     * @param $len             需要的长度
     * @param $special        是否需要特殊符号
     * @return string       返回随机字符串
     */
    static function getRandomStr($len, $special = false) {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if ($special) {
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
        }
        return $str;
    }

    function sendSubscribeMsg($touser, $template_id, $page, $data, $miniprogram_state = null, $lang = null) {
        $token = $this->token->token();
        if ($token) {
            $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$token}";
            return Request::post_json($url, json_encode([
                'touser' => $touser,
                'template_id' => $template_id,
                'page' => $page,
                'data' => $data,
                'miniprogram_state' => $miniprogram_state,
                'lang' => $lang,
            ]));
        } else {
            return false;
        }
    }

    function balanceTransfers($mchid,  $partner_trade_no, $openid, $amount, $desc) {
        $token = $this->token->token();
        if ($token && strlen($openid) > 10) {
            $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
            $data = [
                'mch_appid' => $this->appid,
                'mchid' => $mchid,
                'nonce_str' => self::getRandomStr(32),
                'partner_trade_no' => $partner_trade_no,
                'openid' => $openid,
                'amount' => $amount,
                'desc' => $desc,
                'check_name' => 'NO_CHECK',
            ];
            $sign = WxSign::getSign($data);
            $data['sign'] = $sign;
            Request::post_xml($url, $data, [
                'certPath' => __DIR__ . '/../wxCert/apiclient_cert.pem',
                'keyPath' => __DIR__ . '/../wxCert/apiclient_key.pem',
            ]);
            return true;
        } else {
            return false;
        }
    }
}
